package com.example.ylsys.plants.presenter;

import android.content.Context;
import android.content.Intent;

import com.example.ylsys.plants.Utils.AesUtils;
import com.example.ylsys.plants.base.BasePresenter;
import com.example.ylsys.plants.base.MyApplication;
import com.example.ylsys.plants.bean.BackResultBean;
import com.example.ylsys.plants.bean.LoginParamsBean;
import com.example.ylsys.plants.bean.LoginUserBean;
import com.example.ylsys.plants.contract.WelcomingContract;
import com.example.ylsys.plants.model.WelcomingModel;
import com.google.gson.Gson;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.example.ylsys.plants.Utils.BasicToolUtils.CreateAuthSign;
import static com.example.ylsys.plants.Utils.BasicToolUtils.GetSignature;
import static com.example.ylsys.plants.Utils.BasicToolUtils.getTime;

public class WelcomingPresenter extends BasePresenter<WelcomingContract.View> implements WelcomingContract.Presenter{
    private WelcomingContract.Role_Model model;
    String timestamp;
    private LoginUserBean loginUserVm=new LoginUserBean();
    MyApplication gloVar;
    /**
     * 初始化Retrofit
     */
    public WelcomingPresenter(){
        model=new WelcomingModel();
    }

    @Override
    public void get_role(LoginParamsBean loginParamsBean) {
        //View是否绑定 如果没有绑定，就不执行网络请求
        if (!isViewAttached()) {
            return;
        }
        timestamp = getTime();
        String signature = null;
        String nonce = AesUtils.generateKey();
        try {
            Map<String, String> signature_paras = new HashMap<>();
            signature_paras.put("nonce", nonce);
            signature_paras.put("clientid", loginParamsBean.getClientid());
            signature_paras.put("timestamp", timestamp);
            signature_paras.put("action", "auth");
            signature = GetSignature(loginParamsBean.getMd5Secret(), signature_paras);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> url_paras = new HashMap<>();
        url_paras.put("nonce", nonce);
        url_paras.put("timestamp", timestamp);
        url_paras.put("signature", signature);
        url_paras.put("action", "auth");
        Map<String, String> post_paras = new HashMap<String, String>();
        post_paras.put("clientid", loginParamsBean.getClientid());
        post_paras.put("clienttype", "phone");
        model.post_Api( url_paras,post_paras)
            .subscribeOn(Schedulers.io())
                .flatMap(new Function<BackResultBean, ObservableSource<LoginUserBean>>() {
                    @Override
                    public ObservableSource<LoginUserBean> apply(BackResultBean backResultBean) throws Exception {
                        Gson gson = new Gson();
                        loginUserVm = gson.fromJson(backResultBean.getResult(), LoginUserBean.class);
                        return Observable.just(loginUserVm);
                    }
                })
                .flatMap(new Function<LoginUserBean, ObservableSource<BackResultBean>>() {
                    @Override
                    public ObservableSource<BackResultBean> apply(LoginUserBean loginUserBean) throws Exception {
                        timestamp = getTime();
                        String nonce = AesUtils.generateKey();
                        Map<String, String> signature_paras = new HashMap<>();
                        signature_paras.put("nonce", nonce);
                        signature_paras.put("clientid", loginUserBean.getSessionId());
                        signature_paras.put("timestamp", timestamp);
                        signature_paras.put("action", "phonemenu");
                        signature_paras.put("appname", "plantapp");
                        String signature = null;
                        try {
                            signature = GetSignature(loginUserBean.getToken(), signature_paras);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Map<String, String> url_paras = new HashMap<>();
                        url_paras.putAll(signature_paras);
                        url_paras.put("signature", signature);
                        return model.role_get_Api(url_paras);
                    }
                })
                .doOnNext(new Consumer<BackResultBean>() {
                    @Override
                    public void accept(BackResultBean backResult) throws Exception {
                        loginUserVm.setMenuJson(backResult.getResult());
                    }
                })
                .flatMap(new Function<BackResultBean, ObservableSource<BackResultBean>>() {
                    @Override
                    public ObservableSource<BackResultBean> apply(BackResultBean backResult) throws Exception {
                        timestamp = getTime();
                        String sid=loginUserVm.getSessionId();
                        String token=loginUserVm.getToken();
                        Map<String, String> map = new HashMap<>();
                        String nonce = AesUtils.generateKey();
                        map.put("sid", sid);
                        map.put("timestamp", timestamp);
                        map.put("nonce", nonce);
                        map.put("signature", CreateAuthSign(token, timestamp, nonce, sid));
                        map.put("action", "plantbody");
                        map.put("token", token);
                        return model.get_Api(map);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BackResultBean>() {
                    @Override
                    public void accept(BackResultBean backResult) throws Exception {
                        loginUserVm.setPlantBodyJson(backResult.getResult());
                        mView.hideLoading();
                        mView.onSuccess(loginUserVm);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mView.onError(throwable);
                        mView.hideLoading();
                    }
                });
    }
    @Override
    public LoginParamsBean get_userParams(Context context) {
        mView.showLoading();
        LoginParamsBean loginParamsBean= model.get_userParams(context);
        return loginParamsBean;
    }

}
